import 'dart:convert';
import 'package:get/get.dart';
import '../services/Storage.dart';

class CartController extends GetxController {
  final cartList = [].obs; // 购物车数据
  final isCheckedAll = false.obs; // 是否全选
  final allPrice = 0.0.obs; // 被选中商品总价

  CartController() {
    init();
  }

  // 初始化
  init() async {
    try {
      var storedCartList = await Storage.getString('cartList');
      if (storedCartList != null) {
        cartList.assignAll(json.decode(storedCartList) as List);
      }
    } catch (e) {
      cartList.assignAll([]);
    }

    isCheckedAll.value = isCheckAll();
    computeAllPrice();
  }

  // 判断购物车中商品是否全选
  bool isCheckAll() {
    if (cartList.isNotEmpty) {
      for (var item in cartList) {
        if (item["checked"] == false) {
          isCheckedAll.value = false;
          return false;
        }
      }
      isCheckedAll.value = true;
      return true;
    }

    isCheckedAll.value = false;
    return false;
  }

  // 计算购物车中被选中商品总价
  void computeAllPrice() {
    double tempAllPrice = 0;
    for (var item in cartList) {
      if (item["checked"] == true) {
        tempAllPrice += item["price"] * item["count"];
      }
    }
    allPrice.value = tempAllPrice;
  }

  // 更新购物车数据
  void updateCartList() {
    init();
  }

  // 改变数量，重新保存
  void changeItemCount() {
    Storage.setString("cartList", json.encode(cartList));
    computeAllPrice();
  }

  // 全选, 反选商品
  void changeCheckAll(bool flag) {
    for (var i = 0; i < cartList.length; i++) {
      cartList[i]["checked"] = flag;
    }
    isCheckedAll.value = flag;
    Storage.setString("cartList", json.encode(cartList));
    computeAllPrice();
  }

  // 根据商品id从购物车中删除对应商品
  void removeItemById(String id) {
    cartList.removeWhere((item) => item["_id"] == id);
    Storage.setString("cartList", json.encode(cartList));
  }

  // 删除购物车中被选中的商品
  void removeItem() {
    cartList.removeWhere((item) => item["checked"] == true);
    Storage.setString("cartList", json.encode(cartList));
  }

  // 监听单个checkbox改变
  void itemChangeCheck() {
    isCheckedAll.value = isCheckAll();
    computeAllPrice();
    Storage.setString("cartList", json.encode(cartList));
  }

  // 改变checkbox状态
  void changeCheckState() {
    Storage.setString("cartList", json.encode(cartList));
  }
}
